<template>
  <div class="page-container">
    <el-card class="box-card">
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item label="代理id:">
          <el-input clearable style="width: 120px" v-model="filterForm.agencyId" placeholder="请输入代理id" />
        </el-form-item>
        <el-form-item label="tg用户id:">
          <el-input clearable style="width: 120px" v-model="filterForm.tgUserId" placeholder="请输入tg用户id" />
        </el-form-item>
        <el-form-item label="用户名:">
          <el-input clearable style="width: 120px" v-model="filterForm.tgUserName" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="content-container">
        <!-- 左侧代理菜单 -->
        <AgentFilterMenu v-if="!isMobile" :active-agent-id="filterForm.agencyId" @select-agent="handleAgentSelect"
          class="agent-menu-container" />

        <!-- 右侧表格 -->
        <div class="table-container">
          <!-- 表格 -->
          <el-table v-loading="loading" :data="tableData" border style="width: 100%; overflow-y: auto"
            @selection-change="handleSelectionChange">
            <el-table-column prop="agencyId" label="代理id" :width="isMobile ? 105 : null"/>
            <el-table-column prop="tgUserId" label="tg用户id" :width="isMobile ? 105 : null"/>
            <el-table-column prop="tgUserName" label="用户名" />
            <el-table-column :width="isMobile ? 120 : null" prop="balance" label="账户trx余额">
              <template #default="scope">
                {{ formatBalance(scope.row.balance) }}
              </template>
            </el-table-column>
            <el-table-column :width="isMobile ? 120 : null" prop="usdtBalance" label="账户usdt余额">
              <template #default="scope">
                {{ formatBalance(scope.row.usdtBalance) }}
              </template>
            </el-table-column>
             <el-table-column prop="createTime" label="创建时间" :width="isMobile ? 155 : null"/>
          </el-table>

          <!-- 分页 -->
          <el-pagination class="pagination" :class="{ 'mobile-pagination': isMobile }"
            :current-page="pagination.currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pagination.pageSize"
            :layout="paginationLayout" :total="pagination.total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange"></el-pagination>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from "vue";
import api from "../../network/api";
import AgentFilterMenu from "../../components/AgentFilterMenu.vue";
import { ElMessage } from "element-plus";
import { useWindowSize } from "@vueuse/core";
export default {
  components: {
    AgentFilterMenu,
  },
  setup() {
    const isMobile = computed(() => windowWidth.value < 768);
    const { width: windowWidth } = useWindowSize();
    const filterForm = ref({
      agencyId: '',
      tgUserId: '',
      tgUserName: '',
    });

    const tableData = ref([]);
    const loading = ref(false);
    const multipleSelection = ref([]);

    const botUsernameWidth = ref(0);
    const botPathWidth = ref(0);

    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });
    const lastFetchParams = ref(null);

    const handleAgentSelect = (agentId) => {
      filterForm.value.agencyId = agentId;
      onSearch();
    };
    // 格式化余额显示
    const formatBalance = (balance) => {
      // 检查是否为空值（null、undefined或空字符串）
      if (balance == null || balance === "") {
        return 0;
      }

      return Number(balance / 1e6).toLocaleString("zh-CN", {
        maximumFractionDigits: 10,
      });
    };
        const paginationLayout = computed(() => {
      if (windowWidth.value < 768) {
        return 'sizes, prev, pager, next';
      } else {
        return 'total,sizes, prev, pager, next, jumper';
      }
    });
    const calculateColumnWidths = () => {
      const measureElement = document.createElement("span");
      measureElement.style.position = "absolute";
      measureElement.style.visibility = "hidden";
      measureElement.style.whiteSpace = "nowrap";
      document.body.appendChild(measureElement);

      const getTextWidth = (text) => {
        measureElement.textContent = text;
        return measureElement.offsetWidth;
      };

      let maxBotUsernameWidth = 0;
      let maxBotPathWidth = 0;

      // 计算表头宽度
      maxBotUsernameWidth = Math.max(
        maxBotUsernameWidth,
        getTextWidth("代理机器人名称")
      );
      maxBotPathWidth = Math.max(
        maxBotPathWidth,
        getTextWidth("代理机器人路由")
      );

      // 计算表格数据宽度
      tableData.value.forEach((row) => {
        maxBotUsernameWidth = Math.max(
          maxBotUsernameWidth,
          getTextWidth(row.botUsername)
        );
        maxBotPathWidth = Math.max(maxBotPathWidth, getTextWidth(row.botPath));
      });

      // 适当增加一些间距
      botUsernameWidth.value = maxBotUsernameWidth;
      botPathWidth.value = maxBotPathWidth;

      document.body.removeChild(measureElement);
    };

    watch(
      tableData,
      () => {
        calculateColumnWidths();
      },
      { immediate: true }
    );

    // 获取代理列表
    const fetchAgencyList = () => {

      const params = {
        pageNum: pagination.value.currentPage,
        pageSize: pagination.value.pageSize,
        agencyId: filterForm.value.agencyId,
        tgUserId: filterForm.value.tgUserId,
        ...filterForm.value,
      };
      const isSameAsLast = JSON.stringify(params) === JSON.stringify(lastFetchParams.value);

      if (isSameAsLast) {
        // console.log("参数未变化，跳过请求");
        return;
      }
      loading.value = true;
      api
        .user_userList(params)
        .then((res) => {
          if (res.data.code === 99999 && res.data.success) {
            tableData.value = res.data.data.list;
            pagination.value.total = res.data.data.total;
            lastFetchParams.value = params;
          } else {

            // ElMessage.error(res.msg || "获取代理列表失败");
          }
        })
        .catch((error) => {
          console.error("获取代理列表出错:", error);
          ElMessage.error("请求失败，请稍后重试");
        })
        .finally(() => {
          loading.value = false;
        });
    };

    // 搜索
    const onSearch = () => {
      const hasChanges = Object.keys(filterForm.value).some(key =>
        filterForm.value[key] !== (lastFetchParams.value?.[key] ?? null)
      );

      if (!hasChanges && pagination.value.currentPage === 1) {
        // ElMessage.info("搜索条件未变化");
        return;
      }
      pagination.value.currentPage = 1;
      fetchAgencyList();
    };

    // 重置筛选
    const resetFilter = () => {
      const isAlreadyReset = Object.values(filterForm.value).every(val => val === null);

      if (isAlreadyReset) {
        // ElMessage.info("已处于重置状态");
        return;
      }
      filterForm.value = {
        agencyId: '',
        tgUserId: '',
        tgUserName: '',
      };
      onSearch();
    };

    // 表格选择
    const handleSelectionChange = (val) => {
      multipleSelection.value = val;
    };

    // 分页大小变化
    const handleSizeChange = (size) => {
      pagination.value.pageSize = size;
      fetchAgencyList();
    };

    // 当前页变化
    const handleCurrentChange = (page) => {
      console.log(`当前页: ${page}`);
      pagination.value.currentPage = page;
      fetchAgencyList();
    };

    // 新增用户
    const handleAdd = () => {
      ElMessage.info("新增代理");
    };

    // 编辑用户
    const handleEdit = (row) => {
      ElMessage.info(`编辑代理: ${row.botUsername}`);
    };

    onMounted(() => {
      fetchAgencyList();
    });

    return {
      filterForm,
      tableData,
      loading,
      multipleSelection,
      pagination,
      onSearch,
      resetFilter,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      formatBalance,
      isMobile,
      botUsernameWidth,
      botPathWidth,
      handleAgentSelect,
      paginationLayout
    };
  },
};
</script>

<style scoped lang="less">
.box-card {
  width: 100%;
  height: 90vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;

  &::-webkit-scrollbar {
    width: 1px;
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(248, 248, 250, 0.2);
    border-radius: 6px;
    transition: background 0.3s;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  .demo-form-inline {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    flex: 1;
    margin-bottom: 0;
  }

  .operation-buttons {
    margin-bottom: 20px;
    float: right;
    margin-right: 30px;
  }

  .content-container {
    display: flex;
    flex: 1;
    flex-direction: row;
  }

  .agent-menu-container {
    width: 240px;
    margin-right: 16px;
    flex-shrink: 0;
    max-height: 79.9vh;
  }

  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
    max-height: 79.9vh;

    .el-table {
      flex: 1;
      max-height: 80vh;

    }

    .pagination {
      margin-top: 15px;
      float: right !important;
      display: flex;
      justify-content: flex-end;
      width: 100%;
    }
  }
}

// 将分页显示在最下面
.pagination {
  margin-top: 20px;
  float: right;
}

@media screen and (max-width: 768px) {
  :deep(.el-table__header) .el-table__cell {
    white-space: nowrap !important;
    text-overflow: clip !important;
    overflow: visible !important;
  }

  :deep(.el-table__header-wrapper) th>.cell {
    white-space: nowrap !important;
    overflow: visible !important;
    text-overflow: clip !important;
    display: inline-block;
    width: auto;
  }

  :deep(.el-table__body) .el-table__cell {
    white-space: nowrap !important;
    text-overflow: clip !important;
    overflow: visible !important;
  }

  .mobile-pagination {
    :deep(.el-pagination) {
      display: flex !important;
      flex-wrap: nowrap !important;
      overflow-x: auto !important;
      padding: 5px 0 !important;
      min-height: 32px !important;
      font-size: 12px !important;

      .el-pagination__sizes {
        font-size: 12px !important;
        transform: scale(0.9) !important;
        transform-origin: left center !important;
        white-space: nowrap !important;
      }

      .btn-prev,
      .btn-next {
        min-width: 24px !important;
        height: 24px !important;
        padding: 0 5px !important;
        margin: 0 2px !important;
      }

      .el-pager {
        li {
          min-width: 24px !important;
          height: 24px !important;
          line-height: 24px !important;
          font-size: 12px !important;
          padding: 0 3px !important;
          margin: 0 2px !important;
        }
      }

      .el-pagination__jump {
        margin-left: 0 !important;
        font-size: 12px !important;

        .el-pagination__editor {
          width: 40px !important;

          .el-input__inner {
            height: 24px !important;
            padding: 0 5px !important;
            font-size: 12px !important;
          }
        }
      }
    }

    .mobile-pagination-info {
      font-size: 12px !important;
      margin-top: 5px !important;
      text-align: center !important;
    }
  }

  :deep(.el-pagination) {
    --el-pagination-button-width: 24px !important;
    --el-pagination-button-height: 24px !important;
    --el-pagination-font-size: 12px !important;
  }

  .pagination {
    margin-top: 20px;
    float: none !important;
  }
}
</style>
